<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */


include_once( APP . "Config/your_define.php" );
App::uses('Sanitize', 'Utility');
App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
	var $helpers = array('Html', 'Paginator', 'Session', 'Js', 'Form', 'Cache', 'Text', 'Time');
    var $components = array('Acl', 'Session', "Email", 'Auth', 'RequestHandler', 'Cookie', 'Common', "File"); //,

    var $als = '';

    /**
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function beforeFilter() {
		if(!isset($_SESSION)) {
		     session_start();
		}

		$params = $this->request->params;

		$this->set('action', $params['action']);
		$this->set('controller', $params['controller']);

		App::uses('Category', 'Model');
		$Category = new Category();

		if( isset($params['prefix']) && $params['prefix'] == 'admin') {
			$this->layout = 'admin';
			$user = $this->Auth->user();
        	$this->set('global_user', $user);

			// Get tin nhắn mới
			App::uses('Contact', 'Model');
			$Contact = new Contact();
			$contacts = $Contact->getAll(array(0));
			$this->set('contacts', $contacts);

		} else {
			$this->Auth->allow();
			$categories = $Category->getAll(0, 'DESC');
			$this->set('menus', $categories);

			$fcategories = $Category->getAll(0, 'ASC');
			foreach($fcategories as $k => $v){
				$v['Category']['childs'] = $Category->getAll($v['Category']['id'], 'ASC');
				$fcategories[$k] = $v;
			}

			$this->set('fmenus', $fcategories);

			// Lay danh sach doi tac
			App::uses('Image', 'Model');
			$Image = new Image();

			$this->set('doitac', $Image->getAll(0));
		}

		// Set als
		$model = Inflector::singularize($this->name);
		$this->als = $model;
		$this->set('als', $model);
	}

	/**
     * Upload file
     *
     * @param FileData  meta
     * @return type  meta
     * @access public
     */
    function _upload($file_data) {
        // Upload avatar
        if (!empty($file_data) && $file_data['error'] == 0) {
            $file = $this->File->upload($file_data);

            $this->File->create_thumb($file);

            return $file;
        } else {
            return '';
        }
    }

    /**
	 * Delete, Lock, Unlock
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function admin_changeStatus( $id = null, $status = 5 ) {

		// Get model tu controller
		$model = Inflector::singularize($this->name);

		$liststatus = array(
			4 => 'Unlock',
			5 => 'Lock',
			9 => 'Delete'
		);

		if( in_array( $this->Auth->user('role'), array( 1,2) ) ) {

			if(empty( $id )) {
				$this->Session->setFlash( __('%s member Fail. User Not Found.', $liststatus[$status]), 'error');
			} else {
				$this->$model->id = (int)$id;

				if( $this->$model->saveField('status', (int)$status ) ) {
					$this->Session->setFlash( __('%s member success.', $liststatus[$status]), 'success');
				} else {
					$this->Session->setFlash( __('%s member fail.', $liststatus[$status]), 'error');
				}
			}
		} else {
			$this->Session->setFlash( 'You are not allowed to execute the function of this.', 'error');
		}

		$this->redirect('/admin/'.$this->name);
	}

	/**
     * Chuyen loi tu invalid sang array de xuat len form
     *
     * @param type  meta
     * @return type  meta
     * @access public
     */
    function _getErrorForInvalidJson($errors = null, $model = "") {

        $ret = array();
        if (empty($errors))
            return $ret;

        foreach ($errors as $k => $msg) {
            $k = ucfirst($k);

            // van con mang
            if (empty($msg[0])) {
                foreach ($msg as $k1 => $_msg) {
                    $k1 = ucfirst($k1);
                    if (empty($_msg[0])) {
                        foreach ($_msg as $k2 => $_msg2) {
                            $k2 = ucfirst($k2);
                            $ret[] = array('id' => $model . $k . $k1 . $k2, 'msg' => $_msg2[0]);
                        }
                    } else
                        $ret[] = array('id' => $model . $k . $k1, 'msg' => $_msg[0]);
                }
            } else
                $ret[] = array('id' => $model . $k, 'msg' => $msg[0]);
        }

        return $ret;
    }

	/**
     * Response for client
     *
     * @param type  meta
     * @return type  meta
     * @access public
     */
    function _responseJson($data) {
        $this->RequestHandler->setContent('json', 'text/x-json');

        echo json_encode($data);

        exit;
    }
}
